package com.easondongh.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.hint.HintShardingValue;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.*;

/**
 * @author donghao
 * @date 2022/9/5 20:37
 */
public class UserTableShardingAlgorithm implements HintShardingAlgorithm<Long> {

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, HintShardingValue<Long> shardingValue) {
        Set<String> actualTableNames = new HashSet<>();
        Iterator<Long> iterator = shardingValue.getValues().iterator();
        while (iterator.hasNext()) {
            Long id = iterator.next();
            String actualTableName = shardingValue.getLogicTableName() + "_" + ((id % 2) + 1);
            if(!availableTargetNames.contains(actualTableName)) {
                throw new RuntimeException("不存在的实际表：" + actualTableName);
            }
            actualTableNames.add(actualTableName);
        }
        return new ArrayList<>(actualTableNames);
    }
}
